﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data.SqlClient;

namespace Test
{
    class DBHelper
    {
        //创建链接数据库
        public static string conn="server=.;database=Students;Integrated Security=true";

        public static SqlConnection Con = null;

        //初始化数据库连接
        public static void IntoConnection()
        {
            if (Con == null)
            {
                 Con = new SqlConnection(conn);
            }
            if (Con.State==System.Data.ConnectionState.Closed)
            {
                Con.Open();
            }
            if (Con.State==System.Data.ConnectionState.Broken)
            {
                Con.Close();
                Con.Open();
            }
        }
        //增删改
        public static bool GetNonQuery(string sql)
        {
            IntoConnection();
            SqlCommand cmd = new SqlCommand(sql,Con);
            int i = cmd.ExecuteNonQuery();
            Con.Close();
            return i > 0;
           
        }
        //读取
        public static SqlDataReader Select(string Sql)
        {
            IntoConnection();
            SqlConnection sql = new SqlConnection();
            Con.Open();
            SqlCommand cmd = new SqlCommand(Sql, Con);
            return cmd.ExecuteReader(System.Data.CommandBehavior.CloseConnection);
        }


        //聚合函数
        public static object Scalar(string Sca)
        {
            SqlConnection sql = new SqlConnection();
            Con.Open();
            SqlCommand cmd = new SqlCommand(Sca, Con);
            object final = cmd.ExecuteScalar();
            Con.Close();
            return final;
        }

    }
}
